#ifndef MAINCONTROLLER_H
#define MAINCONTROLLER_H

#include <QObject>
#include <QMutex>
#include <QThread>
#include "motorworker.h"
#include "sensor1worker.h"
#include "sensor2worker.h"
#include "sensor3worker.h"

class MainController : public QObject
{
    Q_OBJECT
public:
    explicit MainController(QObject *parent = nullptr);
    ~MainController();

    int initialize();
    void stopAllSensors();

    void startSensor1(ushort di, ushort d0);
    void startSensor2(ushort di, ushort d0);
    void startSensor3(ushort di, ushort d0, int startCount, int endCount);
    void startSensor4(ushort di, ushort d0, int startCount, int endCount);
    void startMotorButton(ushort di, ushort d0);
    void startStopButton(ushort di, ushort d0);
    void startEmergencyButton(ushort di, ushort d0);

    void emergencyStop();
    void closeAllDO();

signals:
    void logMessage(const QString &message);
    void encoderCountUpdated(long encoderCount, long position);
    void motorStarted();
    void motorStopped();

private slots:
    void updateEncoderCount();

private:
    QTimer *m_encoderTimer;
    QMutex m_mutex;

    // 传感器线程
    QThread *m_sensor1Thread;
    Sensor1Worker *m_sensor1Worker;
    bool m_sensor1Running = false;

    QThread *m_sensor2Thread;
    Sensor2Worker *m_sensor2Worker;
    bool m_sensor2Running = false;

    QThread *m_sensor3Thread;
    Sensor3Worker *m_sensor3Worker;
    bool m_sensor3Running = false;

    QThread *m_sensor4Thread;
    Sensor3Worker *m_sensor4Worker; // 复用Sensor3Worker
    bool m_sensor4Running = false;

    // 按钮线程
    QThread *m_motorButtonThread;
    MotorWorker *m_motorWorker;
    bool m_motorRunning = false;

    QThread *m_stopButtonThread;
    MotorWorker *m_stopWorker;
    bool m_stopRunning = false;

    QThread *m_emergencyButtonThread;
    MotorWorker *m_emergencyWorker;
    bool m_emergencyRunning = false;
};

#endif // MAINCONTROLLER_H
